<?php
/**
 * Created by PhpStorm.
 * User: Lin Hui
 * Date: 2017/5/23
 * Time: 13:53
 */

namespace Common\Model;


use Think\Model;

class SettingModel extends Model
{
    /**
     * @param $key
     * @return mixed
     */
    public function getSetting($key)
    {
        return $this->where(array('key'=>$key))->getField('val');
    }

    /**
     * @param $key
     * @param $val
     * @return bool|mixed
     */
    public function setSetting($key, $val)
    {
        return $this->where(array('key'=>$key))->count() ?
            $this->where(array('key'=>$key))->save(array('val'=>$val)) !== false :
            $this->add(array('key'=>$key, 'val'=>$val));
    }

    /**
     * 获取站点信息
     */
    public function getWebsiteInfo()
    {
        return $this->getSettingByPrefix('website_info');
    }

    /**
     * 通过前缀获取设置
     * @param string $prefix
     * @return array
     */
    public function getSettingByPrefix($prefix)
    {
        $list = $this->where(array("key"=>array('like', $prefix.'.%')))->field('key, val')->select();
        $res = array();
        foreach($list as $item) {
            $res[str_replace($prefix.'.', '', $item['key'])] = $item['val'];
        }
        return $res;
    }

    /**
     * 保存设置通过前缀
     * @param $prefix
     * @param $setting
     * @return bool
     */
    public function setSettingByPrefix($prefix, $setting)
    {
       foreach($setting as $key => $item) {
           $map = array('key'=>$prefix.'.'.$key);
           if(
               $this->where($map)->count()
                   ? ($this->where($map)->save(array('val'=>$item)) === false)
                   : !$this->add(array('key'=>$prefix.'.'.$key, 'val'=>$item))
           ) {
               return false;
           }
       }
       return true;
    }

    /**
     * 页面信息
     * @param $page
     * @return array
     */
    public function getPageInfo($page)
    {
        return array(
            'key'=>$page,
            'banner'=>$this->getSetting("website_info.page.{$page}.banner"),
            'content'=>$this->getSetting("website_info.page.{$page}.content"),
            'thumb'=>$this->getSetting("website_info.page.{$page}.thumb"),
        );
    }
}